package com.gitee.kamismile.stoneComEx.util.view.excelView;

import com.gitee.kamismile.stoneComEx.common.component.base.AbstractXSSFExcelView;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import com.gitee.kamismile.stoneComEx.util.ExcelUtil;
import com.gitee.kamismile.stoneComEx.util.view.ExcelBean;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;

import java.awt.Color;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: lidong
 * Date: 12-3-10
 * Time: 上午11:32
 * 一行一列
 */
public class DeatilReportExcelView extends AbstractXSSFExcelView {

    private CellStyle table1BodyStyle;
    private CellStyle headStyle;
    private CellStyle table2BodyStyle;
    private Font headFont;

    @Override
    protected void buildExcelDocument(
            Map<String, Object> model,
            Workbook workbook,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        List<ExcelBean> excelBeans = new ArrayList<ExcelBean>();


        if (model.get("excelBean") != null) {
            excelBeans.add((ExcelBean) model.get("excelBean"));
        } else {
            excelBeans.addAll((List<ExcelBean>) model.get("excelBeans"));
        }

        new ExcelUtil().expData((SXSSFWorkbook)workbook, excelBeans.get(0));//第一个


        for( int excelBeanNum=1;excelBeanNum<excelBeans.size();excelBeanNum++){
            excelBody((SXSSFWorkbook)workbook, excelBeans.get(excelBeanNum), excelBeanNum);
        }



        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);


        String fileName=excelBeans.get(0).getFileName();
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        else{
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        response.setHeader("Content-Disposition", MessageFormat.format("attachment; filename={0}.xlsx",
                fileName ));
    }

    private void excelBody(SXSSFWorkbook workbook, ExcelBean excelBean, int excelNumber) {

        if(headFont==null) getHeadFont(workbook);
        if(headStyle==null) getHeadStyle(workbook);
        if(table1BodyStyle==null) getTable1BodyStyle(workbook);
        if(table2BodyStyle==null) getTable2BodyStyle(workbook);

        List<String[][]> colmons;
        SXSSFSheet sheet;
        SXSSFRow row;
        Object[] createTimes;
        List<Map<String, Object>> list;
        int cellNum = 2;
        int rowNumber = 1;
        colmons = excelBean.getMuchColmons();
        sheet = (SXSSFSheet) workbook.createSheet(excelBean.getSheetName());
        row = (SXSSFRow) sheet.createRow(0);

        SXSSFCell cellTemp = (SXSSFCell) row.createCell(0);
        cellTemp.setCellStyle(headStyle);
        cellTemp.setCellValue("media");

        cellTemp = (SXSSFCell) row.createCell(1);
        cellTemp.setCellStyle(headStyle);
        cellTemp.setCellValue("Parameter");

        if (excelNumber == 2){
            cellTemp = (SXSSFCell) row.createCell(2);
            cellTemp.setCellStyle(headStyle);
            cellTemp.setCellValue("Ad Location");
        }
        createTimes = null;
        list = excelBean.getMaps().get(1);
        for (Map<String, Object> objectMap : list) {
            if (ValueUtils.isNotNull(objectMap.get("createTimes")))
                createTimes = (Object[]) objectMap.get("createTimes");
        }

        if (excelNumber == 2)
            cellNum = 3;
        if (ValueUtils.isNotNull(createTimes)) {
            for (Object time : createTimes) {
                cellTemp= (SXSSFCell) row.createCell(cellNum++);
                cellTemp.setCellStyle(headStyle);
                cellTemp.setCellValue(ValueUtils.isStringNull(time));
            }
        }
        int i=0;
        for (Map<String, Object> objectMap : excelBean.getMaps().get(0)) {
            SXSSFRow row2 = (SXSSFRow) sheet.createRow(rowNumber);
            SXSSFCell cell = (SXSSFCell) row2.createCell(0);
            cell.setCellValue(ValueUtils.isStringNull(objectMap.get("mediaName")));
            cell.setCellStyle(i % 2 == 0 ? table1BodyStyle : table2BodyStyle);
            sheet.addMergedRegion(new CellRangeAddress(rowNumber, rowNumber + colmons.get(0).length - 1, 0, 0));
            if (excelNumber == 2) {
                cell = (SXSSFCell) row2.createCell(2);
                cell.setCellStyle(i % 2 == 0 ? table1BodyStyle : table2BodyStyle);
                cell.setCellValue(ValueUtils.isStringNull(objectMap.get("locationName")));
                sheet.addMergedRegion(new CellRangeAddress(rowNumber, rowNumber + colmons.get(0).length - 1, 2, 2));
            }


            rowNumber = bodyColmons(
                    colmons, sheet, excelNumber + 1, rowNumber, objectMap, row2,
                    excelNumber==2?"locationReports":"mediaReports",i%2==0?table1BodyStyle:table2BodyStyle);
              i++;
        }
    }




    private int bodyColmons(List<String[][]> colmons,
                            SXSSFSheet sheet, int cellNum, int rowNumber, Map<String, Object> objectMap,
                            SXSSFRow row2, String report,CellStyle cellStyle) {
        SXSSFCell cell;
        for (int col = 0; col < colmons.get(0).length; col++) {
            int colNumber = 0;
            SXSSFRow row3;
            if (col == 0) {
                row3 = row2;
            } else {
                row3 = (SXSSFRow) sheet.createRow(col + rowNumber);
            }
            cell = (SXSSFCell) row3.createCell(1);
            cell.setCellValue(new XSSFRichTextString(colmons.get(0)[col][1]));
            cell.setCellStyle(cellStyle);

            List<Map<String, Object>> reports = (List<Map<String, Object>>) objectMap.get(report);


            if (reports != null && !reports.isEmpty()) {
                for (Map<String, Object> map : reports) {
                    cell = (SXSSFCell) row3.createCell(colNumber + cellNum);
                    cell.setCellValue(new XSSFRichTextString
                            (ValueUtils.isStringNull(map.get(colmons.get(0)[col][0]))));
                    cell.setCellStyle(cellStyle);
                    colNumber++;
                }
            }
        }
        rowNumber = rowNumber + colmons.get(0).length;
        return rowNumber;
    }


    private void getHeadStyle(SXSSFWorkbook workbook) {

        XSSFCellStyle xheadStyle = (XSSFCellStyle) workbook.createCellStyle();
        xheadStyle.setFont(headFont);
        xheadStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        xheadStyle.setAlignment(HorizontalAlignment.CENTER);
//        headStyle.setWrapText(true);
        xheadStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        xheadStyle.setFillForegroundColor( new XSSFColor(new byte[]{(byte)102,(byte)102,(byte)153}));
        this.headStyle=xheadStyle;
    }

    private void getHeadFont(SXSSFWorkbook workbook) {
        headFont = workbook.createFont();
        headFont.setBold(true);
        headFont.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
    }

    private void getTable2BodyStyle(SXSSFWorkbook workbook) {
        table2BodyStyle=getBodyStyle(workbook,table2BodyStyle);
//        table2BodyStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
//        table2BodyStyle.setFillForegroundColor(XSSFColor.CORAL.index);
    }



    private void getTable1BodyStyle(SXSSFWorkbook workbook) {
        XSSFCellStyle xtable1BodyStyle= (XSSFCellStyle) getBodyStyle(workbook, table1BodyStyle);
        xtable1BodyStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        xtable1BodyStyle.setFillForegroundColor( new XSSFColor(new byte[]{(byte)218,(byte)239,(byte)244}));
        this.table1BodyStyle=xtable1BodyStyle;
    }

    private CellStyle getBodyStyle(SXSSFWorkbook workbook,CellStyle xssFCellStyle) {
        xssFCellStyle = workbook.createCellStyle();
        xssFCellStyle.setAlignment(HorizontalAlignment.CENTER);
        xssFCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        xssFCellStyle.setBorderTop(BorderStyle.THIN);
        xssFCellStyle.setBorderBottom(BorderStyle.THIN);
        xssFCellStyle.setBorderLeft(BorderStyle.THIN);
        xssFCellStyle.setBorderRight(BorderStyle.THIN);
        xssFCellStyle.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        xssFCellStyle.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        xssFCellStyle.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        xssFCellStyle.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        return xssFCellStyle;
    }
}
